import axios from 'axios';
import store from 'store';
import moment from 'moment';
import Vue from 'vue';
import * as qiniu from 'qiniu-js';

import {
  MessageBox
} from 'element-ui';
const $alert = MessageBox.alert;

axios.defaults.withCredentials = true;

const service = new axios.create({
  // baseURL: process.env.NODE_ENV === 'development' ? 'https://www.manlitech.com/manli/' : '/manli/',
  baseURL: process.env.NODE_ENV === 'development' ? '/dev/' : '/manli/',
  responseType: 'json',
  timeout: 60 * 1000,
  validateStatus(status) {
    return status >= 200 && status < 300;
  }
});

const getFileImgSize = function (file) {
  return new Promise(resole => {
    let reader = new FileReader();
    reader.onload = function (e) {
      let data = e.target.result;
      let image = new Image();
      image.onload = function () {
        let width = image.width;
        let height = image.height;
        resole({
          width: width,
          height: height
        });
      };
      image.src = data;
    };
    reader.readAsDataURL(file);
  });
}

const notCheck = ['login/loginForToken', 'api/wechatopen/getUserLoginByScanQrcode', 'wechat/getCodeFromWechatAuth'];
const apiKey = 'EIHBZ-JRJWG-2AIQI-IKDTM-6ZMO2-UTB3R';
const baseImgURL = 'https://qiniu.manlitech.com';
const qiniuCode = {
  "614": "文件已存在"
};

export default class Request {
  static notLoginAlert = false;

  static post(url, data, needAlert = true, hasLogin = true, hasWeChart = false) {
    let config = {};
    if (hasLogin && notCheck.indexOf(url) === -1) {
      let authToken = store.state.global.authToken;
      if (authToken === null) {
        if (!this.notLoginAlert) {
          this.notLoginAlert = true;
          $alert('登录超时，请重新登录', '提示').then(() => {
            window.location.href = '/cms/';
          });
        }
        throw '登录超时，请重新登录';
      }

      let headersData = {};
      if (hasWeChart) {
        headersData.auth_token_wechat = authToken;
      } else {
        headersData.auth_token = authToken;
      }

      config = {
        headers: headersData
      };
    }

    return service.post(url, data, config).then(res => {
      res = res.data;
      let code = res.code;
      if (code !== 0) {
        if (code === -2) {
          if (!this.notLoginAlert) {
            this.notLoginAlert = true;
            $alert('登录超时，请重新登录', '提示').then(() => {
              window.location.href = '/cms/';
            });
          }
          throw res.msg;
        }
        let msg = `${res.msg}(错误代码:${code})`;
        if (needAlert) {
          throw new Error(msg);
        } else {
          throw msg;
        }
      }

      let rows = res.rows;
      if (rows === null) {
        return {
          data: res.data,
          msg: res.msg,
          systemTime: res.systemTime
        };
      }
      return {
        data: res.data,
        rows,
        msg: res.msg,
        systemTime: res.systemTime
      };
    }).catch(error => {
      if (typeof error !== 'string') {
        $alert(error.message, '错误');
      }
      throw error;
    });
  }

  static postMapService(url, data = {}) {
    url = 'https://apis.map.qq.com/ws/' + url;
    data.key = apiKey;
    data.output = 'jsonp';
    return Vue.jsonp(url, data).then(res => {
      let status = res.status;
      if (status === 0) {
        return res.result;
      }
      throw new Error(res.message);
    }).catch(error => {
      if (typeof error !== 'string') {
        $alert(error.message, '错误');
      }
      throw error;
    });
  }

  static async postImgToQiniu(file, token, callback) {
    let size = await getFileImgSize(file);
    let flag = size.width > 1000 || size.height > 1000;
    return new Promise((resolve, reject) => {
      let name = file.name;
      let key = `${moment().format('YYYYMMDDHHmmss')}${name}`;
      let observable = qiniu.upload(file, key, token, {
        fname: name,
        params: {}
      }, {
        useCdnDomain: true,
        disableStatisticsReport: true
      });
      let self = this;
      observable.subscribe({
        next(event) {
          if (callback !== undefined) {
            callback(event.total);
          }
        },
        error(errorObj) {
          reject(errorObj);
        },
        complete(res) {
          let key = res.key;
          let imgUrl = `${baseImgURL}/${key}`;
          if (flag) {
            imgUrl += '?imageMogr/thumbnail/1000x1000/auto-orient';
          } else {
            imgUrl += '?imageMogr/auto-orient';
          }
          let fileData = {
            fileName: key,
            fileSize: file.size,
            mimeType: file.type,
            qiqiuUrl: imgUrl,
            status: 1,
            type: 2
          };

          self.saveFileData(fileData).then(() => {
            resolve(imgUrl);
          }).catch(error => {
            reject(error);
          });
        }
      });
    });
  }

  static async postFileToQiniu({
    file,
    fileName,
    token,
    callback,
    key,
    type = 1
  }) {
    return new Promise((resolve, reject) => {
      if (fileName === undefined) {
        fileName = file.name;
      }
      if (key === undefined) {
        key = `${moment().format('YYYYMMDDHHmmss')}${fileName}`;
      }
      let observable = qiniu.upload(file, key, token, {
        fname: fileName,
        params: {}
      }, {
        useCdnDomain: true,
        disableStatisticsReport: true
      });

      let self = this;
      observable.subscribe({
        next(event) {
          if (callback !== undefined) {
            callback(event.total);
          }
        },
        error(errorObj) {
          let code = errorObj.code;
          let msg = qiniuCode[code];
          if (msg !== undefined) {
            $alert(msg, '错误');
          }
          reject(errorObj);
        },
        complete(res) {
          let key = res.key;
          let imgUrl = `${baseImgURL}/${key}`;
          let fileType = file.type;
          if (fileType.startsWith('image/')) {
            imgUrl += '?imageMogr/auto-orient';
          }

          let fileData = {
            fileName: key,
            type: type,
            fileSize: file.size,
            mimeType: file.type,
            qiqiuUrl: imgUrl,
            status: 1
          };
          self.saveFileData(fileData).then(() => {
            resolve(imgUrl);
          }).catch(error => {
            reject(error);
          });
        }
      });
    });
  }

  static saveFileData(fileData) {
    const apiName = 'api/aqiniufiles/save';
    return this.post(apiName, fileData).then(res => {
      return res;
    });
  }
};
